﻿#region Librerias

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using ESF.General.Entity;
using ESF.SFT.Entities;
using ESF.General.Text;
using System.Collections.Specialized;
using ESF.General;
using ESF.SFT.Service.Messages;
using System.IO;
using ESF.SFT.Service.FileReceiveLogger;
using ESF.SFT.Service.FileReplicator;
using ESF.General.Network;

#endregion


namespace ESF.SFT.Service
{
	[WebService(Namespace = "http://sft.esf.com/")]
	[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
	public class ReceiverClassic : System.Web.Services.WebService
	{
		[WebMethod]
		public void UploadFile(string pSessionTicket, string pFileName, string pUserName, string pMD5Hash, byte[] pMessageContent)
		{
			FileUploadMessage fileUploadMessage = new FileUploadMessage ()
			{
				SessionTicket = pSessionTicket,
				FileName = pFileName,
				UserName = pUserName,
				FileLengthBytes = pMessageContent.Length,
				MD5Hash = pMD5Hash,
				FileUploadContent = new MemoryStream ()
			};
			
			fileUploadMessage.FileUploadContent.Write (pMessageContent, 0, pMessageContent.Length);
			fileUploadMessage.FileUploadContent.Position = 0;

			UploadFile (fileUploadMessage);
		}


		public static void UploadFile(FileUploadMessage pFileUploadMessage)
		{
			string replicatorDestinationCopy;

			string publishedFileName;
			string publishedFileNameBackup;
			string tmpFileName;

			string guid = Guid.NewGuid ().ToString ();
						

			#region Preparacion de Rutas
			
			publishedFileName = Path.Combine(ReadConfig.GetAppSetting("PublishFolder"), pFileUploadMessage.FileName);
			publishedFileNameBackup = Path.Combine (
				ReadConfig.GetAppSetting("PublishFolderBackup"), 
				pFileUploadMessage.ShortIdentificator, 
				DateTime.Now.Year.ToString (), 
				DateTime.Now.Month.ToString ().PadLeft (2, '0'),
				DateTime.Now.Day.ToString().PadLeft(2, '0'),
				string.Format ("{0}__{1}{2}",
					FileHelper.GetFileNameFirstPoint (pFileUploadMessage.FileName),
					guid,
					FileHelper.GetFileNameExtensionFromFirstPoint (pFileUploadMessage.FileName)));

			FileHelper.EnsureFolder(publishedFileName);
			FileHelper.EnsureFolder(publishedFileNameBackup);

			#endregion
			
			#region Copia y verificación a Temporal
						
			tmpFileName = FileHelper.GenerateTempFileName ();

			using (FileStream writer = new FileStream(tmpFileName, FileMode.Create))
			{
				pFileUploadMessage.FileUploadContent.CopyTo(writer);
			}

			if (TextHelper.GetMD5HashFile(tmpFileName) != pFileUploadMessage.MD5Hash)
			{
				throw new GenericInfoException (string.Format ("El contenido del archivo enviado no coincide con el esperado, debe ser reenviado el archivo {0}", pFileUploadMessage.FileName));
			}

			#endregion

			#region Copiar a publicacion
			
			FileHelper.Delete(publishedFileNameBackup);
			FileHelper.Delete(publishedFileName);

			FileHelper.Copy(tmpFileName, publishedFileNameBackup);
			FileHelper.Copy(tmpFileName, publishedFileName);

			FileHelper.Delete(tmpFileName);

			using (FileReceiveLoggerClient frlc = new FileReceiveLoggerClient())
			{
				frlc.LogFileReceive(
					new Entities.FileReceiveLog()
					{
						FileName = Path.GetFileName(publishedFileName),
						LengthBytes = pFileUploadMessage.FileLengthBytes,
						UploadDateTime = DateTime.Now,
						UploadUserAlias = pFileUploadMessage.UserName,
						UserHostAddress = HttpContext.Current.Request.UserHostAddress,	
						ServerHostName = HttpContext.Current.Request.Url.Host,			
						ServerHostAddress = HttpContext.Current.Request.ServerVariables["LOCAL_ADDR"],
						IdentificationTypeCode = pFileUploadMessage.IdentificationTypeCode,
						IdentificationNumber = pFileUploadMessage.IdentificationNumber,
						ShortIdentificator = pFileUploadMessage.ShortIdentificator,
						MD5Hash = pFileUploadMessage.MD5Hash,
						GUID = guid
					});
			}

			replicatorDestinationCopy = ReadConfig.GetAppSetting("ESF.SFT.Replicator.CopyDestination", string.Empty);

			if (!string.IsNullOrEmpty(replicatorDestinationCopy))
			{
				new FileReplicatorClient().Copy(replicatorDestinationCopy, pFileUploadMessage.UserName, Path.GetFileName(publishedFileNameBackup), FileHelper.GetFileStream(publishedFileNameBackup));
			}

			#endregion
		}
	}
}
